#!/usr/bin/env node

// 部署API服务
const express = require('express')
const { exec } = require('child_process')
const path = require('path')
const fs = require('fs')

const app = express()
const PORT = 3012

// 中间件
app.use(express.json())
app.use(express.static('public'))

// 应用配置
const APPS = {
  'login-app': { port: 3003, path: 'micro-apps/login-app' },
  'system-app': { port: 3005, path: 'micro-apps/system-app' },
  'dashboard-app': { port: 3007, path: 'micro-apps/dashboard-app' },
  'tenant-app': { port: 3009, path: 'micro-apps/tenant-app' },
  'tool-app': { port: 3006, path: 'micro-apps/tool-app' },
  'workflow-app': { port: 3008, path: 'micro-apps/workflow-app' },
  'monitor-app': { port: 3010, path: 'micro-apps/monitor-app' }
}

// 执行命令的Promise包装
function execCommand(command, cwd = process.cwd()) {
  return new Promise((resolve, reject) => {
    exec(command, { cwd }, (error, stdout, stderr) => {
      if (error) {
        reject({ error: error.message, stderr })
      } else {
        resolve({ stdout, stderr })
      }
    })
  })
}

// 获取应用状态
app.get('/api/apps/status', async (req, res) => {
  try {
    const status = {}
    
    for (const [appName, config] of Object.entries(APPS)) {
      try {
        // 检查Docker容器状态
        const { stdout } = await execCommand(`docker ps --filter name=${appName} --format "{{.Status}}"`)
        status[appName] = {
          name: appName,
          port: config.port,
          status: stdout.trim() ? 'running' : 'stopped',
          version: 'v1.0.0',
          environment: 'production',
          lastDeploy: new Date().toISOString()
        }
      } catch (error) {
        status[appName] = {
          name: appName,
          port: config.port,
          status: 'error',
          error: error.message
        }
      }
    }
    
    res.json(status)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

// 部署单个应用
app.post('/api/apps/:appName/deploy', async (req, res) => {
  const { appName } = req.params
  const { environment = 'production', version = 'latest' } = req.body
  
  if (!APPS[appName]) {
    return res.status(404).json({ error: '应用不存在' })
  }
  
  try {
    // 执行部署脚本
    const deployScript = path.join(__dirname, 'scripts', 'deploy-app.sh')
    const command = `bash ${deployScript} ${appName} ${environment} ${version}`
    
    const result = await execCommand(command)
    
    res.json({
      success: true,
      message: `${appName} 部署成功`,
      output: result.stdout
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      output: error.stderr
    })
  }
})

// 批量部署
app.post('/api/apps/deploy-all', async (req, res) => {
  const { environment = 'production', version = 'latest' } = req.body
  
  try {
    const deployScript = path.join(__dirname, 'scripts', 'deploy-all.sh')
    const command = `bash ${deployScript} ${environment} ${version}`
    
    const result = await execCommand(command)
    
    res.json({
      success: true,
      message: '批量部署成功',
      output: result.stdout
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      output: error.stderr
    })
  }
})

// 回滚应用
app.post('/api/apps/:appName/rollback', async (req, res) => {
  const { appName } = req.params
  
  if (!APPS[appName]) {
    return res.status(404).json({ error: '应用不存在' })
  }
  
  try {
    const deployScript = path.join(__dirname, 'scripts', 'deploy-app.sh')
    const command = `bash ${deployScript} ${appName} rollback`
    
    const result = await execCommand(command)
    
    res.json({
      success: true,
      message: `${appName} 回滚成功`,
      output: result.stdout
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      output: error.stderr
    })
  }
})

// 获取部署日志
app.get('/api/apps/:appName/logs', async (req, res) => {
  const { appName } = req.params
  
  if (!APPS[appName]) {
    return res.status(404).json({ error: '应用不存在' })
  }
  
  try {
    // 获取Docker容器日志
    const { stdout } = await execCommand(`docker logs --tail 100 ${appName}`)
    
    const logs = stdout.split('\n').map(line => ({
      time: new Date().toLocaleTimeString(),
      message: line,
      type: line.includes('ERROR') ? 'error' : 
             line.includes('WARN') ? 'warning' : 
             line.includes('SUCCESS') ? 'success' : 'info'
    }))
    
    res.json(logs)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 部署API服务启动成功！`)
  console.log(`📡 服务地址: http://localhost:${PORT}`)
  console.log(`📋 API文档: http://localhost:${PORT}/api/health`)
})
